// Task data storage
let tasks = [];

// Use arrays and mappings to support multiple timers running simultaneously
let runningTimers = [];
let timerIntervals = {};

// Global filter conditions
let activeFilters = {
  status: 'to-process',  // Default to to-process
  dateRange: { start: null, end: null }
};

// ========== Quick Docs & Notes Section ========== //
// 相关代码已迁移到 notes.js

// ========== 备注全屏编辑相关 ========== //
function setupNotesFullscreenEvents() {
  const notesTextarea = document.getElementById('drawer-task-notes');
  const fullscreenBtn = document.getElementById('fullscreen-notes-btn');
  const fullscreenOverlay = document.getElementById('notes-fullscreen-overlay');
  const fullscreenTextarea = document.getElementById('notes-fullscreen-textarea');
  const exitBtn = document.getElementById('exit-fullscreen-notes-btn');

  // 容错处理
  if (!notesTextarea || !fullscreenBtn || !fullscreenOverlay || !fullscreenTextarea || !exitBtn) return;

  // 进入编辑模式时显示全屏按钮
  function updateFullscreenBtnVisibility() {
    if (notesTextarea.style.display !== 'none') {
      fullscreenBtn.style.display = '';
    } else {
      fullscreenBtn.style.display = 'none';
    }
  }

  // 监听编辑模式切换
  if (!window._origSetNotesEditMode) {
    window._origSetNotesEditMode = window.setNotesEditMode;
    window.setNotesEditMode = function(isEditing) {
      window._origSetNotesEditMode.call(this, isEditing);
      updateFullscreenBtnVisibility();
    };
  }

  // 初始隐藏
  updateFullscreenBtnVisibility();

  // 点击全屏按钮
  fullscreenBtn.onclick = function(e) {
    e.stopPropagation();
    fullscreenTextarea.value = notesTextarea.value;
    fullscreenOverlay.style.display = 'block';
    fullscreenTextarea.focus();
  };

  // 退出全屏
  exitBtn.onclick = function() {
    fullscreenOverlay.style.display = 'none';
  };

  // 全屏编辑时自动保存
  fullscreenTextarea.oninput = function() {
    notesTextarea.value = fullscreenTextarea.value;
    if (typeof saveTaskNotes === 'function') {
      saveTaskNotes();
    }
  };
}

// Initialize quick docs & notes on DOMContentLoaded
(function() {
  document.addEventListener('DOMContentLoaded', function() {
    // 初始化备注全屏编辑事件
    setupNotesFullscreenEvents();
  });
})();

// Get current date and set to date input field
document.addEventListener('DOMContentLoaded', function() {
  console.log("DOM content loaded, initializing application...");
  
  // Set default date range (natural week: Monday to Sunday)
  setupDefaultDateRange();
  
  // Load tasks from localStorage if available
  loadTasksToStorage();
  
  // Restore timer states from localStorage
  restoreTimerStates();
  
  // Initialize summary data
  updateSummary();
  
  // Initialize task filtering
  initTaskFilters();
  
  // Initialize date filtering
  initDateFilter();
  
  // Ensure all event listeners are added
  ensureEventListeners();
  
  // Listen for timer state updates from other tabs
  window.addEventListener('storage', function(e) {
    // Prevent circular loading, only process timer state changes
    if (e.key === 'taskTrackerTimerStates') {
      console.log("Timer state change detected, updating timers...");
      restoreTimerStates();
      applyFilters();
    } 
    // Only reload on actual task data changes (add, delete or modify tasks)
    else if (e.key === 'taskTrackerTasks' && e.oldValue !== e.newValue) {
      console.log("Task data change detected, reloading...");
      // Set delay to avoid multiple pages triggering simultaneously
      setTimeout(() => {
        if (!window.isLoadingTasks) {
          loadTasksToStorage();
          applyFilters();
        }
      }, 100);
    }
  });
  
  // Open modal
  document.getElementById('open-task-modal').addEventListener('click', function() {
    const modal = document.getElementById('task-modal');
    modal.classList.add('show');
  });
  
  // Close modal
  document.getElementById('close-modal').addEventListener('click', closeModal);
  document.getElementById('cancel-task').addEventListener('click', closeModal);
  
  // Close modal when clicking outside
  document.getElementById('task-modal').addEventListener('click', function(e) {
    if (e.target === this) {
      closeModal();
    }
  });
  
  // Add task button click event
  document.getElementById('add-task-button').addEventListener('click', function() {
    const taskDescription = document.getElementById('task-description').value.trim();
    const timeSpent = document.getElementById('time-spent').value.trim() || "0";
    const taskStatus = document.getElementById('task-status').value || "Pending";
    const taskTagsInput = document.getElementById('task-tags').value.trim();
    
    // Process tags, converting comma-separated tags to an array
    const tags = taskTagsInput ? taskTagsInput.split(',').map(tag => tag.trim()).filter(tag => tag) : [];
    
    if (taskDescription) {
      const newTaskId = tasks.length > 0 ? Math.max(...tasks.map(t => t.id)) + 1 : 1;
      const newTask = {
        id: newTaskId,
        title: taskDescription,
        time: parseFloat(timeSpent),
        status: taskStatus,
        notes: "No detailed notes",
        timeSpent: parseFloat(timeSpent) * 3600, // Convert hours to seconds
        createdAt: new Date().toISOString(), // Add creation date
        completedAt: null, // 添加完成时间属性，初始为null
        tags: tags // Save tag array
      };
      
      // 如果初始状态就是完成，则立即设置完成时间
      if (taskStatus === 'Completed') {
        newTask.completedAt = new Date().toISOString();
      }
      
      // Add new task to task list at the beginning (because sorting by creation time)
      tasks.unshift(newTask);
      saveTasksToStorage();
      
      // Clear table and re-render all tasks (maintain sorting consistency)
      const tbody = document.getElementById('tasks-tbody');
      if (tbody) {
        tbody.innerHTML = '';
        tasks.forEach(task => {
          addTaskToTable(task);
        });
      } else {
        // If table not found, add this task separately
      addTaskToTable(newTask);
      }
      
      // Clear input fields and close modal
      document.getElementById('task-description').value = '';
      document.getElementById('task-tags').value = '';
      document.getElementById('time-spent').value = '0';
      document.getElementById('task-status').value = 'Pending';
      closeModal();
      
      // Show success notification
      showNotification(`Task "${taskDescription}" successfully added.`, 'success');
      
      // Apply current filter conditions
      applyFilters();
      
      // Update summary data
      updateSummary();
    } else {
      alert('Please enter a task description!');
    }
  });
  
  // Handle task click event
  document.addEventListener('click', function(e) {
    if (e.target.classList.contains('task-title')) {
      const taskRow = e.target.closest('tr');
      if (taskRow) {
      const taskId = parseInt(taskRow.getAttribute('data-id'));
        console.log("Task clicked:", taskId);
        if (taskId) {
      openTaskDrawer(taskId);
        }
      }
    }
  });
  
  // Close drawer events
  document.getElementById('close-drawer').addEventListener('click', function() {
    closeDrawer();
  });
  document.getElementById('drawer-overlay').addEventListener('click', function() {
    closeDrawer();
  });
  
  // Timer toggle button
  document.getElementById('toggle-timer-btn').addEventListener('click', toggleTimer);
  
  // Edit title button event
  document.getElementById('edit-title-btn').addEventListener('click', function() {
    setTitleEditMode(true);
  });
  
  // Save title button event
  document.getElementById('save-task-title').addEventListener('click', saveTaskTitle);
  
  // Cancel title editing
  document.getElementById('cancel-title').addEventListener('click', function() {
    setTitleEditMode(false);
  });
  
  // Edit notes button event
  document.getElementById('edit-notes-btn').addEventListener('click', function() {
    setNotesEditMode(true);
  });
  
  // Save notes button event
  document.getElementById('save-task-notes').addEventListener('click', saveTaskNotes);
  
  // Cancel notes editing
  document.getElementById('cancel-notes').addEventListener('click', function() {
    setNotesEditMode(false);
  });
  
  // Next status button event
  document.getElementById('next-status-btn').addEventListener('click', moveToNextStatus);
  
  // Previous status button event
  document.getElementById('prev-status-btn').addEventListener('click', moveToPrevStatus);
  
  // Delete task button event
  document.getElementById('delete-task-btn').addEventListener('click', showDeleteConfirmation);
  
  // Confirm delete button event
  const confirmDeleteBtn = document.getElementById('confirm-delete');
  if (confirmDeleteBtn) {
    confirmDeleteBtn.addEventListener('click', function() {
      // Default is delete task operation
      confirmDeleteTask.call(this);
    });
  }
  
  // Cancel delete button event
  document.getElementById('cancel-delete').addEventListener('click', closeConfirmDialog);
  
  // Click outside to close confirm dialog
  document.getElementById('confirm-dialog').addEventListener('click', function(e) {
    if (e.target === this) {
      closeConfirmDialog();
    }
  });
  
  // Save timer states before closing/refreshing
  window.addEventListener('beforeunload', function() {
    saveTimerStates();
  });
  
  // 强制默认只显示To Process
  activeFilters.status = 'to-process';
  const filterTabs = document.querySelectorAll('.filter-tab');
  filterTabs.forEach(tab => tab.classList.remove('active'));
  const toProcessTab = document.querySelector('.filter-tab[data-filter="to-process"]');
  if (toProcessTab) toProcessTab.classList.add('active');
  // 页面初始先清空任务表，避免先渲染全部
  const tbody = document.getElementById('tasks-tbody');
  if (tbody) tbody.innerHTML = '';

  // 标签编辑相关事件
  document.getElementById('edit-tags-btn').onclick = function() {
    document.getElementById('edit-tags-container').style.display = '';
    document.getElementById('edit-tags-btn').style.display = 'none';
    // 编辑时隐藏No Tags
    const tagsContainer = document.getElementById('drawer-task-tags');
    if (tagsContainer.textContent === 'No Tags') {
      tagsContainer.textContent = '';
    }
  };
  document.getElementById('cancel-tags-btn').onclick = function() {
    document.getElementById('edit-tags-container').style.display = 'none';
    document.getElementById('edit-tags-btn').style.display = '';
    // 重新渲染标签
    const taskId = parseInt(document.getElementById('drawer-task-notes').getAttribute('data-task-id'));
    const task = tasks.find(t => t.id === taskId);
    const tagsContainer = document.getElementById('drawer-task-tags');
    tagsContainer.innerHTML = '';
    if (task && task.tags && task.tags.length > 0) {
      task.tags.forEach(tag => {
        const tagElement = document.createElement('span');
        tagElement.className = 'task-tag';
        tagElement.textContent = tag;
        tagsContainer.appendChild(tagElement);
      });
    } else {
      tagsContainer.textContent = 'No Tags';
    }
  };
  document.getElementById('save-tags-btn').onclick = function() {
    const input = document.getElementById('edit-tags-input').value;
    const tags = input.split(',').map(t => t.trim()).filter(t => t);
    const taskId = parseInt(document.getElementById('drawer-task-notes').getAttribute('data-task-id'));
    const task = tasks.find(t => t.id === taskId);
    if (task) {
      task.tags = tags;
      saveTasksToStorage();
      openTaskDrawer(taskId); // 重新渲染
      showNotification('Tags updated', 'success');
    }
  };

  var wbBtn = document.getElementById('open-whiteboard-btn');
  if (wbBtn) {
    wbBtn.onclick = function() {
      window.location.href = 'whiteboard.html';
    };
  }
});

// Set default date range (natural week: Monday to Sunday)
function setupDefaultDateRange() {
  const today = new Date();
  const currentDay = today.getDay(); // 0 is Sunday, 1-6 is Monday to Saturday
  
  // Calculate Monday's date
  const monday = new Date(today);
  // If today is Sunday(0), need to go back 6 days; otherwise need to go back (current day - 1) days
  monday.setDate(today.getDate() - (currentDay === 0 ? 6 : currentDay - 1));
  
  // Calculate Sunday's date
  const sunday = new Date(monday);
  sunday.setDate(monday.getDate() + 6);
  
  // Format date as YYYY-MM-DD
  const formatDate = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };
  
  const mondayStr = formatDate(monday);
  const sundayStr = formatDate(sunday);
  
  // Set input field values
  document.getElementById('date-from').value = mondayStr;
  document.getElementById('date-to').value = sundayStr;
  
  // Set global filter conditions
  activeFilters.dateRange = {
    start: monday,
    end: sunday
  };
}

// Initialize date filtering
function initDateFilter() {
  // Apply button click event
  document.getElementById('apply-date-filter').addEventListener('click', function() {
    const fromDate = document.getElementById('date-from').value;
    const toDate = document.getElementById('date-to').value;
    
      // Show table loading status
      const tableWrapper = document.querySelector('.table-wrapper');
      tableWrapper.classList.add('table-loading', 'active');
      
      // Update global filter conditions
    if (fromDate && toDate) {
      // If both dates are set, use date range filtering
      activeFilters.dateRange = {
        start: new Date(fromDate),
        end: new Date(toDate)
      };
    } else {
      // If any date is empty, clear date filtering
      activeFilters.dateRange = {
        start: null,
        end: null
      };
    }
      
      // Apply filtering (add slight delay to show loading effect)
      setTimeout(() => {
        applyFilters();
        // Stop loading status after completion
        tableWrapper.classList.remove('table-loading', 'active');
      }, 400);
  });
}

// Apply all filter conditions
function applyFilters() {
  const tbody = document.getElementById('tasks-tbody');
  if (!tbody) return;
  tbody.innerHTML = '';
  // 过滤出需要显示的任务
  const filteredTasks = tasks.filter(task => {
    let isVisible = true;
    // Apply status filtering
    if (activeFilters.status === 'to-process') {
      const taskStatus = task.status.toLowerCase();
      isVisible = taskStatus === 'pending' || taskStatus === 'in progress';
    } else if (activeFilters.status !== 'all') {
      const statusFilter = activeFilters.status.replace('-', ' ');
      const statusMatch = task.status.toLowerCase() === statusFilter.toLowerCase();
      isVisible = isVisible && statusMatch;
      // Apply date filtering (effective for filtering other than to-process)
      if (isVisible && activeFilters.dateRange.start && activeFilters.dateRange.end) {
        const isCompletedFilter = statusFilter.toLowerCase() === 'completed';
        const taskDate = isCompletedFilter && task.completedAt 
          ? new Date(task.completedAt) 
          : (task.createdAt ? new Date(task.createdAt) : new Date());
        const taskDateOnly = new Date(taskDate.getFullYear(), taskDate.getMonth(), taskDate.getDate());
        const startDateOnly = new Date(
          activeFilters.dateRange.start.getFullYear(),
          activeFilters.dateRange.start.getMonth(),
          activeFilters.dateRange.start.getDate()
        );
        const endDateOnly = new Date(
          activeFilters.dateRange.end.getFullYear(), 
          activeFilters.dateRange.end.getMonth(), 
          activeFilters.dateRange.end.getDate()
        );
        endDateOnly.setHours(23, 59, 59, 999);
        const dateInRange = taskDateOnly >= startDateOnly && taskDateOnly <= endDateOnly;
        isVisible = isVisible && dateInRange;
      }
    } else {
      // Apply date filtering (effective for "all" filtering)
      if (activeFilters.dateRange.start && activeFilters.dateRange.end) {
        const isCompleted = task.status.toLowerCase() === 'completed';
        const taskDate = isCompleted && task.completedAt 
          ? new Date(task.completedAt) 
          : (task.createdAt ? new Date(task.createdAt) : new Date());
        const taskDateOnly = new Date(taskDate.getFullYear(), taskDate.getMonth(), taskDate.getDate());
        const startDateOnly = new Date(
          activeFilters.dateRange.start.getFullYear(),
          activeFilters.dateRange.start.getMonth(),
          activeFilters.dateRange.start.getDate()
        );
        const endDateOnly = new Date(
          activeFilters.dateRange.end.getFullYear(), 
          activeFilters.dateRange.end.getMonth(), 
          activeFilters.dateRange.end.getDate()
        );
        endDateOnly.setHours(23, 59, 59, 999);
        const dateInRange = taskDateOnly >= startDateOnly && taskDateOnly <= endDateOnly;
        isVisible = isVisible && dateInRange;
      }
    }
    return isVisible;
  });
  // 只渲染过滤后的任务
  filteredTasks.forEach(task => addTaskToTable(task));
  // 更新 summary
  updateFilteredSummary();
}

// Save multiple timer states to chrome.storage.local
function saveTimerStates() {
  if (!(window.chrome && chrome.storage && chrome.storage.local)) {
    console.error('chrome.storage.local 不可用，无法保存计时器状态');
    return;
  }
  if (runningTimers.length > 0) {
    const timerStates = runningTimers.map(taskId => {
      const task = tasks.find(t => t.id === taskId);
      if (!task) return null;
      const now = Date.now();
      const timerInfo = timerIntervals[taskId];
      const elapsedTime = Math.floor((now - timerInfo.startTime) / 1000);
      task.timeSpent = elapsedTime;
      const hours = elapsedTime / 3600;
      task.time = parseFloat(hours.toFixed(1));
      return {
        taskId: taskId,
        startTime: timerInfo.startTime,
        elapsedTime: elapsedTime,
        isRunning: true,
        timestamp: now
      };
    }).filter(state => state !== null);
    // Save timer states and updated task data
    chrome.storage.local.set({
      taskTrackerTimerStates: timerStates,
      taskTrackerTasks: tasks
    });
    // Dispatch custom event to notify other tabs
    const event = new CustomEvent('timer-state-updated', { detail: { timerStates } });
    window.dispatchEvent(event);
    // 通知background.js开始闪烁
    if (chrome.runtime && chrome.runtime.sendMessage) {
      chrome.runtime.sendMessage({ type: 'timerBlink', blink: true });
    }
  } else {
    // If no timers are running, clear stored timer states
    chrome.storage.local.remove('taskTrackerTimerStates');
    // Dispatch custom event to notify other tabs
    const event = new CustomEvent('timer-state-updated', { detail: { timerStates: [] } });
    window.dispatchEvent(event);
    // 通知background.js停止闪烁
    if (chrome.runtime && chrome.runtime.sendMessage) {
      chrome.runtime.sendMessage({ type: 'timerBlink', blink: false });
    }
  }
}

// Restore multiple timer states from chrome.storage.local
function restoreTimerStates() {
  if (!(window.chrome && chrome.storage && chrome.storage.local)) {
    console.error('chrome.storage.local 不可用，无法恢复计时器状态');
    return;
  }
  // 1. 清理本地所有timer
  Object.values(timerIntervals).forEach(info => {
    if (info && info.interval) clearInterval(info.interval);
  });
  runningTimers = [];
  timerIntervals = {};
  // 2. 读取storage，重建timer
  chrome.storage.local.get(['taskTrackerTimerStates'], function(result) {
    const timerStates = result.taskTrackerTimerStates || [];
    timerStates.forEach(timerState => {
      if (timerState.isRunning) {
        startTimerForTask(timerState.taskId, timerState.elapsedTime, timerState.startTime, true); // skipSave
      }
    });
  });
}

// 页面初始化时增加chrome.storage.onChanged监听，保证多标签页同步
if (window.chrome && chrome.storage && chrome.storage.onChanged) {
  chrome.storage.onChanged.addListener(function(changes, areaName) {
    if (areaName === 'local' && (changes.taskTrackerTimerStates || changes.taskTrackerTasks)) {
      restoreTimerStates();
      if (typeof applyFilters === 'function') applyFilters();
    }
  });
}

// Save tasks to chrome.storage.local
function saveTasksToStorage() {
  //window.chrome && chrome.storage && chrome.storage.local
  console.log('saveTasksToStorage', window.chrome, chrome.storage, chrome.storage.local);
  if (!(window.chrome && chrome.storage && chrome.storage.local)) {
    console.error('chrome.storage.local 不可用，无法保存任务');
    return;
  }
  chrome.storage.local.set({ taskTrackerTasks: tasks });
}

// Load tasks from chrome.storage.local
function loadTasksToStorage() {
  if (!(window.chrome && chrome.storage && chrome.storage.local)) {
    console.error('chrome.storage.local 不可用，无法加载任务数据');
    tasks = [];
    setTimeout(() => {
      window.isLoadingTasks = false;
      console.log("Task loading status reset");
      applyFilters();
    }, 200);
    return;
  }
  if (window.isLoadingTasks) {
    console.log("Task data already loading, skipping...");
    return;
  }
  window.isLoadingTasks = true;
  console.log("Loading task data...");
  try {
    chrome.storage.local.get(['taskTrackerTasks'], function(result) {
      const storedTasks = result.taskTrackerTasks;
      if (storedTasks) {
        const oldTaskCount = tasks.length;
        const newTasks = storedTasks;
        console.log(`Successfully parsed ${newTasks.length} tasks`);
        tasks = newTasks;
        tasks.forEach(task => {
          if (!task.createdAt) {
            task.createdAt = new Date().toISOString();
          }
        });
        tasks.sort((a, b) => {
          const dateA = new Date(a.createdAt || 0);
          const dateB = new Date(b.createdAt || 0);
          return dateB - dateA;
        });
      } else {
        console.log("No task data found in storage");
        tasks = [];
      }
      setTimeout(() => {
        window.isLoadingTasks = false;
        console.log("Task loading status reset");
        applyFilters();
      }, 200);
    });
  } catch (error) {
    console.error("Error parsing task data:", error);
    tasks = [];
    setTimeout(() => {
      window.isLoadingTasks = false;
      console.log("Task loading status reset");
      applyFilters();
    }, 200);
  }
}

// Close modal
function closeModal() {
  const modal = document.getElementById('task-modal');
  modal.classList.remove('show');
}

// Open task drawer
function openTaskDrawer(taskId) {
  console.log("Attempting to open task drawer, task ID:", taskId);
  
  // Remove automatic data reload logic to avoid infinite loop
  // if (tasks.length === 0) {
  //   console.log("Task list empty, attempting to reload data");
  //   loadTasksToStorage();
  // }
  
  const task = tasks.find(t => t.id === taskId);
  if (!task) {
    console.error("Task ID not found:", taskId);
    return;
  }
  
  try {
    // Ensure DOM elements exist
    const elements = [
      'drawer-task-title', 
      'drawer-task-status', 
      'drawer-task-created-date',
      'drawer-task-completed-date',
      'drawer-task-tags',
      'drawer-task-notes', 
      'notes-display',
      'next-status-btn',
      'prev-status-btn',
      'delete-task-btn',
      'toggle-timer-btn',
      'drawer-overlay',
      'task-drawer'
    ];
    
    // Check all required DOM elements
    for (const id of elements) {
      if (!document.getElementById(id)) {
        console.error(`DOM element not found: ${id}`);
        // 但是允许completed-date-section不存在，因为它是新添加的
        if (id !== 'drawer-task-completed-date') {
          return;
        }
      }
    }
    
    document.getElementById('drawer-task-title').textContent = task.title;
    document.getElementById('drawer-task-status').textContent = task.status;
    
    // Update status badge
    updateStatusBadge(task.status);
    
    // Set creation date
    const createdDateElement = document.getElementById('drawer-task-created-date');
    if (task.createdAt) {
      const createdDate = new Date(task.createdAt);
      const formattedDate = formatDateForDisplay(createdDate);
      createdDateElement.textContent = formattedDate;
    } else {
      createdDateElement.textContent = 'Unknown';
    }
    
    // 设置完成时间（如果有）
    updateCompletedTimeDisplay(task);
    
    // Display tags
    const tagsContainer = document.getElementById('drawer-task-tags');
    tagsContainer.innerHTML = '';
    if (task.tags && task.tags.length > 0) {
      task.tags.forEach(tag => {
        const tagElement = document.createElement('span');
        tagElement.className = 'task-tag';
        tagElement.textContent = tag;
        tagsContainer.appendChild(tagElement);
      });
    } else {
      tagsContainer.textContent = 'No Tags';
    }
    
    // 初始化编辑输入框
    document.getElementById('edit-tags-input').value = (task.tags || []).join(',');
    document.getElementById('edit-tags-container').style.display = 'none';
    document.getElementById('edit-tags-btn').style.display = '';
    
    // Set notes content
    const notesText = task.notes || 'No detailed notes';
    document.getElementById('drawer-task-notes').value = notesText;
    
    // Format and display notes with links
    updateNotesDisplay(notesText);
    
    // Store the task ID
    document.getElementById('drawer-task-notes').setAttribute('data-task-id', taskId);
    document.getElementById('next-status-btn').setAttribute('data-task-id', taskId);
    document.getElementById('prev-status-btn').setAttribute('data-task-id', taskId);
    document.getElementById('delete-task-btn').setAttribute('data-task-id', taskId);
    document.getElementById('toggle-timer-btn').setAttribute('data-task-id', taskId);
    
    // Update button states based on current status
    updateStatusButtonStates(task);
    
    // Update timer UI status
    const isTaskRunning = runningTimers.includes(taskId);
    updateTimerButtonUI(isTaskRunning);
    
    // Update displayed time
    updateTimerDisplay(taskId);
    
    // Disable timer button if task is completed
    const toggleBtn = document.getElementById('toggle-timer-btn');
    toggleBtn.disabled = task.status === 'Completed';
    
    // Reset edit mode
    setNotesEditMode(false);
    
    // Reset title edit mode
    setTitleEditMode(false);
    
    // Show drawer
    console.log("Displaying task drawer");
    document.getElementById('drawer-overlay').style.display = 'block';
    document.getElementById('task-drawer').classList.add('open');
    
    // Successfully opened
    console.log("Successfully opened task drawer:", task.title);
    // 每次打开抽屉时重新绑定全屏按钮事件
    setupNotesFullscreenEvents();
  } catch (error) {
    console.error("Error opening task drawer:", error);
  }
}

// Format date display function
function formatDateForDisplay(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  
  // Get hours, minutes
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}`;
}

// Close task drawer
function closeDrawer() {
  document.getElementById('drawer-overlay').style.display = 'none';
  document.getElementById('task-drawer').classList.remove('open');
}

// Directly format time display from seconds
function formatTimeFromSeconds(seconds) {
  if (seconds >= 3600) {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    
    if (minutes > 0) {
      return `${hours}h ${minutes}min`;
    } else {
      return `${hours}h`;
    }
  } else {
    const minutes = Math.floor(seconds / 60);
    return `${minutes}min`;
  }
}

// Add new task to table
function addTaskToTable(task) {
  const tbody = document.getElementById('tasks-tbody');
  const newRow = document.createElement('tr');
  newRow.setAttribute('data-id', task.id);
  
  const taskCell = document.createElement('td');
  const taskTitle = document.createElement('span');
  taskTitle.classList.add('task-title');
  taskTitle.textContent = task.title;
  taskCell.appendChild(taskTitle);
  
  const timeCell = document.createElement('td');
  timeCell.textContent = formatTimeFromSeconds(task.timeSpent);
  
  // Modify status cell, add background-colored status indicator
  const statusCell = document.createElement('td');
  const statusBadge = document.createElement('span');
  statusBadge.textContent = task.status;
  
  // Apply status badge style
  applyStatusBadgeStyle(statusBadge, task.status);
  
  statusCell.appendChild(statusBadge);
  
  const timerCell = document.createElement('td');
  timerCell.classList.add('timer-indicator-cell');
  const timerIndicator = document.createElement('div');
  timerIndicator.classList.add('timer-indicator');
  timerIndicator.style.display = 'none';
  timerCell.appendChild(timerIndicator);
  
  newRow.appendChild(taskCell);
  newRow.appendChild(timeCell);
  newRow.appendChild(statusCell);
  newRow.appendChild(timerCell);
  
  tbody.appendChild(newRow);
  
  // If task is running, show timer indicator
  if (runningTimers.includes(task.id)) {
    showTimerIndicator(task.id);
  }
}

// Timer functions
function toggleTimer() {
  const taskId = parseInt(document.getElementById('toggle-timer-btn').getAttribute('data-task-id'));
  if (!taskId) return;
  
  const isRunning = runningTimers.includes(taskId);
  
  if (isRunning) {
    stopTimerForTask(taskId);
    updateTimerButtonUI(false);
  } else {
    const task = tasks.find(t => t.id === taskId);
    if (task) {
      // Ensure timeSpent is a number
      const timeSpent = typeof task.timeSpent === 'number' ? task.timeSpent : 0;
      startTimerForTask(taskId, timeSpent);
      updateTimerButtonUI(true);
      
      // Show status notification
      showNotification(`Timer started: ${task.title}`, 'success');
    }
  }
}

function updateTimerButtonUI(isRunning) {
  const toggleBtn = document.getElementById('toggle-timer-btn');
  const playIcon = document.getElementById('timer-icon-play');
  const pauseIcon = document.getElementById('timer-icon-pause');
  
  if (isRunning) {
    toggleBtn.classList.add('running');
    playIcon.style.display = 'none';
    pauseIcon.style.display = 'inline';
  } else {
    toggleBtn.classList.remove('running');
    playIcon.style.display = 'inline';
    pauseIcon.style.display = 'none';
  }
}

function updateTimerDisplay(taskId) {
  const timerElement = document.getElementById('task-timer');
  if (!timerElement) return;
  
  const task = tasks.find(t => t.id === taskId);
  if (!task) return;
  
  const timeValue = task.timeSpent || 0;
  
  // Update timer display
  const formattedTime = formatTime(timeValue);
  timerElement.textContent = formattedTime;
}

function formatTime(seconds) {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = seconds % 60;
  
  return [
    hours.toString().padStart(2, '0'),
    minutes.toString().padStart(2, '0'),
    secs.toString().padStart(2, '0')
  ].join(':');
}

// Update summary data
function updateSummary() {
  const totalTasks = tasks.length;
  
  let totalSeconds = 0;
  tasks.forEach(task => {
    totalSeconds += task.timeSpent || 0;
  });
  
  // Update summary display
  document.getElementById('total-tasks').textContent = totalTasks;
  document.getElementById('total-time').textContent = formatTimeFromSeconds(totalSeconds);
}

// Toggle notes edit mode
function setNotesEditMode(isEditing) {
  const displayElement = document.getElementById('notes-display');
  const editElement = document.getElementById('drawer-task-notes');
  const actionsElement = document.getElementById('notes-actions');
  const formatTipElement = document.querySelector('.format-tip');

  // 只要 displayElement、editElement、actionsElement 存在即可
  if (!displayElement || !editElement || !actionsElement) return;

  if (isEditing) {
    displayElement.style.display = 'none';
    editElement.style.display = 'block';
    actionsElement.style.display = 'flex';
    if (formatTipElement) formatTipElement.style.display = 'block';
  } else {
    displayElement.style.display = 'block';
    editElement.style.display = 'none';
    actionsElement.style.display = 'none';
    if (formatTipElement) formatTipElement.style.display = 'none';
  }
}

// Save task notes
function saveTaskNotes() {
  const notesElement = document.getElementById('drawer-task-notes');
  const taskId = parseInt(notesElement.getAttribute('data-task-id'));
  const updatedNotes = notesElement.value.trim();
  
  const taskIndex = tasks.findIndex(t => t.id === taskId);
  if (taskIndex !== -1) {
    tasks[taskIndex].notes = updatedNotes || 'No detailed notes';
    
    // Save to localStorage
    saveTasksToStorage();
    
    // Update the display with formatted links
    updateNotesDisplay(tasks[taskIndex].notes);
    
    // Switch back to display mode
    setNotesEditMode(false);
  }
}

// Format notes with links
function updateNotesDisplay(text) {
  if (!text) return;
  
  // First replace line breaks with <br> to preserve formatting
  let formattedText = text;
  
  // Replace [text](url) with actual links
  formattedText = formattedText.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank">$1</a>');
  
  // Set the HTML to display notes
  document.getElementById('notes-display').innerHTML = formattedText;
}

// Define status progression
const statusOrder = ['Pending', 'In Progress', 'Completed'];

// Move to next status
function moveToNextStatus() {
  const taskId = parseInt(this.getAttribute('data-task-id'));
  const taskIndex = tasks.findIndex(t => t.id === taskId);
  
  if (taskIndex !== -1) {
    const currentStatus = tasks[taskIndex].status;
    const currentIndex = statusOrder.indexOf(currentStatus);
    
    // If current status is in our progression and not at the end
    if (currentIndex !== -1 && currentIndex < statusOrder.length - 1) {
      tasks[taskIndex].status = statusOrder[currentIndex + 1];
      updateTaskStatus(taskIndex);
      
      // If moving to completed, stop timer
      if (tasks[taskIndex].status === 'Completed' && runningTimers.includes(taskId)) {
        stopTimerForTask(taskId);
        updateTimerButtonUI(false);
      }
    } else if (currentIndex === -1) {
      // If status is not in our progression (like 'New'), set to first status
      tasks[taskIndex].status = statusOrder[0];
      updateTaskStatus(taskIndex);
    }
    
    // Update timer button status
    const toggleBtn = document.getElementById('toggle-timer-btn');
    if (toggleBtn) {
      toggleBtn.disabled = tasks[taskIndex].status === 'Completed';
    }
  }
}

// Move to previous status
function moveToPrevStatus() {
  const taskId = parseInt(this.getAttribute('data-task-id'));
  const taskIndex = tasks.findIndex(t => t.id === taskId);
  
  if (taskIndex !== -1) {
    const currentStatus = tasks[taskIndex].status;
    const currentIndex = statusOrder.indexOf(currentStatus);
    
    // If current status is in our progression and not at the beginning
    if (currentIndex > 0) {
      tasks[taskIndex].status = statusOrder[currentIndex - 1];
      updateTaskStatus(taskIndex);
    } else if (currentIndex === -1) {
      // If status is not in our progression (like 'New'), set to first status
      tasks[taskIndex].status = statusOrder[0];
      updateTaskStatus(taskIndex);
    }
    
    // Update timer button status
    const toggleBtn = document.getElementById('toggle-timer-btn');
    if (toggleBtn) {
      toggleBtn.disabled = tasks[taskIndex].status === 'Completed';
    }
  }
}

// Common function to update task status
function updateTaskStatus(taskIndex) {
  // 检查是否刚变成完成状态，如果是则记录完成时间
  if (tasks[taskIndex].status === 'Completed' && !tasks[taskIndex].completedAt) {
    tasks[taskIndex].completedAt = new Date().toISOString();
  }

  // 如果从完成状态变更为其他状态，则清除完成时间
  if (tasks[taskIndex].status !== 'Completed' && tasks[taskIndex].completedAt) {
    tasks[taskIndex].completedAt = null;
  }
  
  // Update the task in the table
  updateTaskInTable(tasks[taskIndex]);
  
  // Update status in drawer
  const statusElement = document.getElementById('drawer-task-status');
  if (statusElement) {
    statusElement.textContent = tasks[taskIndex].status;
    updateStatusBadge(tasks[taskIndex].status);
  }

  // 更新完成时间显示
  updateCompletedTimeDisplay(tasks[taskIndex]);
  
  // Update button states
  updateStatusButtonStates(tasks[taskIndex]);
  
  // Save to localStorage
  saveTasksToStorage();
  
  // Update summary
  updateSummary();
}

// Update status buttons state based on task status
function updateStatusButtonStates(task) {
  const prevBtn = document.getElementById('prev-status-btn');
  const nextBtn = document.getElementById('next-status-btn');
  
  if (!prevBtn || !nextBtn) return;
  
  const currentIndex = statusOrder.indexOf(task.status);
  
  // If task status is not in our defined progression
  if (currentIndex === -1) {
    prevBtn.disabled = true;
    nextBtn.disabled = false;
    return;
  }
  
  // Disable prev button if at first status
  prevBtn.disabled = currentIndex === 0;
  
  // Disable next button if at last status
  nextBtn.disabled = currentIndex === statusOrder.length - 1;
}

// Update task in the table
function updateTaskInTable(task, onlyTime = false) {
  const row = document.querySelector(`tr[data-id="${task.id}"]`);
  if (row) {
    // 只更新时间
    if (onlyTime) {
      row.cells[1].textContent = formatTimeFromSeconds(task.timeSpent);
      return;
    }
    row.cells[1].textContent = formatTimeFromSeconds(task.timeSpent);
    // Update status cell
    const statusCell = row.cells[2];
    let statusBadge = statusCell.querySelector('span');
    if (!statusBadge) {
      statusBadge = document.createElement('span');
      statusCell.textContent = '';
      statusCell.appendChild(statusBadge);
    }
    statusBadge.textContent = task.status;
    applyStatusBadgeStyle(statusBadge, task.status);
    // Update timer indicator
    const timerIndicator = row.querySelector('.timer-indicator');
    if (timerIndicator) {
      timerIndicator.style.display = runningTimers.includes(task.id) ? 'block' : 'none';
    }
    // 只有状态变更时才全量刷新
    // 移除原有的自动 applyFilters()
  }
}

// Show delete confirmation dialog
function showDeleteConfirmation() {
  const taskId = parseInt(this.getAttribute('data-task-id'));
  const task = tasks.find(t => t.id === taskId);
  
  if (task) {
    // Set task ID to delete
    document.getElementById('confirm-delete').setAttribute('data-task-id', taskId);
    
    // Customize confirmation message, including task name
    document.getElementById('confirm-message').textContent = `Are you sure you want to delete "${task.title}"?`;
    
    // Show confirmation dialog
    document.getElementById('confirm-dialog').style.display = 'flex';
  }
}

// Show notification message
function showNotification(message, type = 'success', duration = 3000) {
  const notification = document.getElementById('notification');
  const notificationMessage = document.getElementById('notification-message');
  
  // Set message content
  notificationMessage.textContent = message;
  
  // Ensure notification element type is correct
  notification.className = 'notification ' + type;
  
  // Show table loading status
  const tableWrapper = document.querySelector('.table-wrapper');
  tableWrapper.classList.remove('table-loading', 'active');
  
  // Show notification
  notification.classList.add('show');
  
  // Set timer to automatically hide notification
  setTimeout(() => {
    // Apply fade out animation
    notification.style.animation = 'notification-hide 0.4s forwards';
    
    // Animation ends completely hidden and reset
    setTimeout(() => {
      notification.classList.remove('show');
      notification.style.animation = '';
    }, 400);
  }, duration);
}

// Confirm delete task
function confirmDeleteTask() {
  const taskId = parseInt(this.getAttribute('data-task-id'));
  
  // Find task index
  const taskIndex = tasks.findIndex(t => t.id === taskId);
  
  if (taskIndex !== -1) {
    // Save task title for notification
    const taskTitle = tasks[taskIndex].title;
    
    // Stop timer if running for this task
    if (runningTimers.includes(taskId)) {
      stopTimerForTask(taskId);
    }
    
    // Remove from array
    tasks.splice(taskIndex, 1);
    
    // Remove from table
    const row = document.querySelector(`tr[data-id="${taskId}"]`);
    if (row) {
      row.remove();
    }
    
    // Save to localStorage
    saveTasksToStorage();
    
    // Update summary
    updateSummary();
    
    // Close drawer and confirm dialog
    closeDrawer();
    closeConfirmDialog();
    
    // Show delete success notification (using English)
    showNotification(`Task "${taskTitle}" successfully deleted.`, 'success');
  }
}

// Close confirmation dialog
function closeConfirmDialog() {
  document.getElementById('confirm-dialog').style.display = 'none';
  
  // Reset confirm dialog status
  setTimeout(() => {
    // Reset title
    document.querySelector('.confirm-title').textContent = 'Delete Task';
    
    // Reset confirm button text
    document.getElementById('confirm-delete').textContent = 'Delete';
    
    // Clear data-action attribute
    document.getElementById('confirm-delete').removeAttribute('data-action');
  }, 300);
}

// Update status badge
function updateStatusBadge(status) {
  const statusElement = document.getElementById('drawer-task-status');
  
  if (!statusElement) return;
  
  // Reset classes
  statusElement.className = 'drawer-detail';
  
  // Apply appropriate class based on status
  status = status ? status.toLowerCase() : 'new';
  
  if (status.includes('completed')) {
    statusElement.classList.add('completed');
  } else if (status.toLowerCase().includes('progress')) {
    statusElement.classList.add('in-progress');
  } else if (status.toLowerCase().includes('pending')) {
    statusElement.classList.add('pending');
  } else {
    statusElement.classList.add('new');
  }
  
  // Apply consistent style
  applyStatusBadgeStyle(statusElement, status);
}

// Show timer indicator
function showTimerIndicator(taskId) {
  const row = document.querySelector(`tr[data-id="${taskId}"]`);
  if (row) {
    const timerIndicator = row.querySelector('.timer-indicator');
    if (timerIndicator) {
      timerIndicator.style.display = 'block';
    }
  }
}

// Hide timer indicator
function hideTimerIndicator(taskId) {
  const row = document.querySelector(`tr[data-id="${taskId}"]`);
  if (row) {
    const timerIndicator = row.querySelector('.timer-indicator');
    if (timerIndicator) {
      timerIndicator.style.display = 'none';
    }
  }
}

// Apply status badge style
function applyStatusBadgeStyle(element, status) {
  // Apply drawer-specific style
  element.style.padding = '3px 8px';
  element.style.borderRadius = '4px';
  element.style.fontSize = '11px';
  element.style.fontWeight = '500';
  element.style.display = 'inline-block';
  
  // Apply background color and text color based on status
  const statusLower = status.toLowerCase();
  if (statusLower.includes('completed')) {
    element.style.backgroundColor = '#e6f4ea';
    element.style.color = '#137333';
  } else if (statusLower.includes('progress')) {
    element.style.backgroundColor = '#e8f0fe';
    element.style.color = '#1a73e8';
  } else if (statusLower.includes('pending')) {
    element.style.backgroundColor = '#fef7e0';
    element.style.color = '#b06000';
  } else {
    element.style.backgroundColor = '#f1f3f4';
    element.style.color = '#5f6368';
  }
}

// Initialize task filtering
function initTaskFilters() {
  const filterTabs = document.querySelectorAll('.filter-tab');
  
  // Add click event handling
  filterTabs.forEach(tab => {
    tab.addEventListener('click', function() {
      // If already active tag, do nothing
      if (this.classList.contains('active')) return;
      
      // Remove active class from all tags
      filterTabs.forEach(t => t.classList.remove('active'));
      
      // Add active class to current clicked tag
      this.classList.add('active');
      
      // Show loading status
      const tableWrapper = document.querySelector('.table-wrapper');
      tableWrapper.classList.add('table-loading', 'active');
      
      // Update global filter conditions
      activeFilters.status = this.getAttribute('data-filter');
      
      // Apply filtering (add slight delay to show loading effect)
      setTimeout(() => {
        applyFilters();
        // Stop loading status after completion
        tableWrapper.classList.remove('table-loading', 'active');
      }, 300);
    });
  });
}

// Update filtered summary data
function updateFilteredSummary() {
  const visibleRows = Array.from(document.querySelectorAll('#tasks-tbody tr')).filter(
    row => row.style.display !== 'none'
  );
  
  const totalTasks = visibleRows.length;
  
  let totalSeconds = 0;
  visibleRows.forEach(row => {
    const taskId = parseInt(row.getAttribute('data-id'));
    const task = tasks.find(t => t.id === taskId);
    if (task) {
      totalSeconds += task.timeSpent || 0;
    }
  });
  
  // Update summary display
  document.getElementById('total-tasks').textContent = totalTasks;
  document.getElementById('total-time').textContent = formatTimeFromSeconds(totalSeconds);
}

// Ensure all event listeners are added after DOM fully loaded
function ensureEventListeners() {
  // Prevent repeated execution
  if (window.listenersInitialized) {
    return;
  }
  
  console.log("Ensure all event listeners are added...");
  
  // Handle task click event - Global delegation method
  document.addEventListener('click', function(e) {
    if (e.target.classList.contains('task-title')) {
      const taskRow = e.target.closest('tr');
      if (taskRow) {
        const taskId = parseInt(taskRow.getAttribute('data-id'));
        console.log("Task clicked:", taskId);
        if (taskId) {
          openTaskDrawer(taskId);
        }
      }
    }
  });
  
  // Drawer close button
  const closeDrawerBtn = document.getElementById('close-drawer');
  if (closeDrawerBtn) {
    closeDrawerBtn.addEventListener('click', function() {
      closeDrawer();
    });
  }
  
  // Drawer overlay close
  const drawerOverlay = document.getElementById('drawer-overlay');
  if (drawerOverlay) {
    drawerOverlay.addEventListener('click', function() {
      closeDrawer();
    });
  }
  
  // Edit title button event
  const editTitleBtn = document.getElementById('edit-title-btn');
  if (editTitleBtn) {
    editTitleBtn.addEventListener('click', function() {
      setTitleEditMode(true);
    });
  }
  
  // Save title button event
  const saveTitleBtn = document.getElementById('save-task-title');
  if (saveTitleBtn) {
    saveTitleBtn.addEventListener('click', saveTaskTitle);
  }
  
  // Cancel title editing
  const cancelTitleBtn = document.getElementById('cancel-title');
  if (cancelTitleBtn) {
    cancelTitleBtn.addEventListener('click', function() {
      setTitleEditMode(false);
    });
  }
  
  // Edit notes button event
  const editNotesBtn = document.getElementById('edit-notes-btn');
  if (editNotesBtn) {
    editNotesBtn.addEventListener('click', function() {
      setNotesEditMode(true);
    });
  }
  
  // Save notes button event
  const saveNotesBtn = document.getElementById('save-task-notes');
  if (saveNotesBtn) {
    saveNotesBtn.addEventListener('click', saveTaskNotes);
  }
  
  // Next status button event
  const nextStatusBtn = document.getElementById('next-status-btn');
  if (nextStatusBtn) {
    nextStatusBtn.addEventListener('click', moveToNextStatus);
  }
  
  // Previous status button event
  const prevStatusBtn = document.getElementById('prev-status-btn');
  if (prevStatusBtn) {
    prevStatusBtn.addEventListener('click', moveToPrevStatus);
  }
  
  // Delete task button event
  const deleteTaskBtn = document.getElementById('delete-task-btn');
  if (deleteTaskBtn) {
    deleteTaskBtn.addEventListener('click', showDeleteConfirmation);
  }
  
  // Confirm delete button event
  const confirmDeleteBtn = document.getElementById('confirm-delete');
  if (confirmDeleteBtn) {
    confirmDeleteBtn.addEventListener('click', confirmDeleteTask);
  }
  
  // Cancel delete button event
  const cancelDeleteBtn = document.getElementById('cancel-delete');
  if (cancelDeleteBtn) {
    cancelDeleteBtn.addEventListener('click', closeConfirmDialog);
  }
  
  // Timer toggle button
  const timerToggleBtn = document.getElementById('toggle-timer-btn');
  if (timerToggleBtn) {
    timerToggleBtn.addEventListener('click', toggleTimer);
  }
  
  // Mark event listeners initialized
  window.listenersInitialized = true;
}

// Toggle title edit mode
function setTitleEditMode(isEditing) {
  const displayElement = document.getElementById('drawer-task-title');
  const editElement = document.getElementById('drawer-task-title-edit');
  const actionsElement = document.getElementById('title-actions');
  
  if (isEditing) {
    // Switch to edit mode
    const currentTitle = displayElement.textContent;
    editElement.value = currentTitle;
    displayElement.style.display = 'none';
    editElement.style.display = 'block';
    actionsElement.style.display = 'flex';
    editElement.focus();
  } else {
    // Switch back to display mode
    displayElement.style.display = 'block';
    editElement.style.display = 'none';
    actionsElement.style.display = 'none';
  }
}

// Save task title
function saveTaskTitle() {
  const titleElement = document.getElementById('drawer-task-title-edit');
  const taskId = parseInt(document.getElementById('toggle-timer-btn').getAttribute('data-task-id'));
  const updatedTitle = titleElement.value.trim();
  
  if (!updatedTitle) {
    showNotification("Task title cannot be empty", "error");
    return;
  }
  
  const taskIndex = tasks.findIndex(t => t.id === taskId);
  if (taskIndex !== -1) {
    // Store old title for notification
    const oldTitle = tasks[taskIndex].title;
    
    // Update title in task object
    tasks[taskIndex].title = updatedTitle;
    
    // Update title in drawer display
    document.getElementById('drawer-task-title').textContent = updatedTitle;
    
    // Update title in table
    const taskRow = document.querySelector(`tr[data-id="${taskId}"]`);
    if (taskRow) {
      const titleElement = taskRow.querySelector('.task-title');
      if (titleElement) {
        titleElement.textContent = updatedTitle;
      }
    }
    
    // Save to localStorage
    saveTasksToStorage();
    
    // Show success notification
    showNotification(`Task title updated from "${oldTitle}" to "${updatedTitle}"`, 'success');
    
    // Switch back to display mode
    setTitleEditMode(false);
  }
}

// 添加一个新函数用于更新完成时间显示
function updateCompletedTimeDisplay(task) {
  const completedDateElement = document.getElementById('drawer-task-completed-date');
  const completedDateSection = document.getElementById('completed-date-section');
  
  if (completedDateElement && completedDateSection) {
    if (task.completedAt) {
      const completedDate = new Date(task.completedAt);
      const formattedDate = formatDateForDisplay(completedDate);
      completedDateElement.textContent = formattedDate;
      completedDateSection.style.display = 'block';
    } else {
      completedDateElement.textContent = '-';
      completedDateSection.style.display = 'none';
    }
  }
}

// 计时相关核心函数
function startTimerForTask(taskId, elapsedTime = 0, customStartTime = null, skipSave = false) {
  const taskIndex = tasks.findIndex(t => t.id === taskId);
  if (taskIndex === -1) return;

  // Set task status to In Progress (unless it's completed)
  if (tasks[taskIndex].status !== 'Completed' && tasks[taskIndex].status !== 'In Progress') {
    tasks[taskIndex].status = 'In Progress';
    updateTaskInTable(tasks[taskIndex]);
  }

  // 初始化timespends字段
  if (!Array.isArray(tasks[taskIndex].timespends)) {
    tasks[taskIndex].timespends = [];
  }

  // 记录本次计时的开始时间
  const nowISO = new Date().toISOString();
  tasks[taskIndex].timespends.push({ start: nowISO, end: null });

  // Add to running timers list
  if (!runningTimers.includes(taskId)) {
    runningTimers.push(taskId);
  }

  // Clear existing timer (if exists)
  if (timerIntervals[taskId]) {
    clearInterval(timerIntervals[taskId].interval);
  }

  // Use custom start time or calculate start time based on elapsed time
  const startTime = customStartTime || (Date.now() - (elapsedTime * 1000));
  timerIntervals[taskId] = {
    startTime: startTime,
    interval: setInterval(function() {
      updateTaskTimer(taskId, startTime);
    }, 1000)
  };

  // Show timer indicator
  showTimerIndicator(taskId);

  // Immediately update timer display
  updateTaskTimer(taskId, startTime);

  // Save timer state
  if (!skipSave) {
    saveTimerStates();
  }
}

function updateTaskTimer(taskId, startTime) {
  const taskIndex = tasks.findIndex(t => t.id === taskId);
  if (taskIndex === -1) return;
  const now = Date.now();
  const elapsedSeconds = Math.floor((now - startTime) / 1000);
  tasks[taskIndex].timeSpent = elapsedSeconds;
  const hours = elapsedSeconds / 3600;
  tasks[taskIndex].time = parseFloat(hours.toFixed(1));
  // 只更新时间
  updateTaskInTable(tasks[taskIndex], true);
  // 如果当前抽屉显示该任务，也更新时间
  const drawerTaskId = getCurrentDrawerTaskId();
  if (drawerTaskId === taskId) {
    updateTimerDisplay(taskId);
  }
  // 30秒存储一次
  if (elapsedSeconds % 30 === 0) {
    saveTasksToStorage();
  }
}

function getCurrentDrawerTaskId() {
  const element = document.getElementById('toggle-timer-btn');
  return element ? parseInt(element.getAttribute('data-task-id')) : null;
}

function stopTimerForTask(taskId) {
  const taskIndex = tasks.findIndex(t => t.id === taskId);
  if (taskIndex === -1) return;

  const task = tasks[taskIndex];
  const timerInfo = timerIntervals[taskId];

  // 结束本次计时的end时间
  if (Array.isArray(task.timespends) && task.timespends.length > 0) {
    // 找到最后一个end为null的timespend，补上end
    for (let i = task.timespends.length - 1; i >= 0; i--) {
      if (!task.timespends[i].end) {
        task.timespends[i].end = new Date().toISOString();
        break;
      }
    }
  }

  if (timerInfo) {
    clearInterval(timerInfo.interval);
    delete timerIntervals[taskId];

    // 从 runningTimers 移除该任务ID
    const idx = runningTimers.indexOf(taskId);
    if (idx !== -1) runningTimers.splice(idx, 1);

    // Update task状态为Pending
    task.status = 'Pending';
    updateTaskStatus(taskIndex);

    // 隐藏计时器指示
    hideTimerIndicator(taskId);

    // 更新计时显示
    updateTimerDisplay(taskId);

    // 保存timer状态（此时runningTimers已无该任务）
    saveTimerStates();
  }
} 

// Show Today's Tasks 弹窗逻辑（升级：用timespends统计）
function isTodayLocal(date) {
  const now = new Date();
  return (
    date.getFullYear() === now.getFullYear() &&
    date.getMonth() === now.getMonth() &&
    date.getDate() === now.getDate()
  );
}

function getTodayTimeSpentFromTimespends(timespends) {
  if (!Array.isArray(timespends)) return 0;
  const today = new Date();
  const todayStart = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0, 0);
  const todayEnd = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59, 999);
  let total = 0;
  for (const span of timespends) {
    if (!span.start) continue;
    const start = new Date(span.start);
    const end = span.end ? new Date(span.end) : new Date();
    // 只统计和今天有交集的部分
    if (end < todayStart || start > todayEnd) continue;
    const realStart = start < todayStart ? todayStart : start;
    const realEnd = end > todayEnd ? todayEnd : end;
    total += Math.max(0, realEnd - realStart);
  }
  return Math.round(total / 1000); // 返回秒
}

function getTodayTasks(callback) {
  // 优先chrome.storage.local
  function filterTasks(tasks) {
    const todayTasks = [];
    const today = new Date();
    for (const task of tasks || []) {
      let isTodayTask = false;
      let todaySpent = 0;
      let showDate = null;
      if (Array.isArray(task.timespends) && task.timespends.length > 0) {
        // 只要有时间段start或end在今天
        for (const span of task.timespends) {
          if (span.start && isTodayLocal(new Date(span.start))) isTodayTask = true;
          if (span.end && isTodayLocal(new Date(span.end))) isTodayTask = true;
        }
        todaySpent = getTodayTimeSpentFromTimespends(task.timespends);
        showDate = task.timespends[0]?.start || task.createdAt;
      } else {
        // fallback: createdAt/completedAt
        if (task.createdAt && isTodayLocal(new Date(task.createdAt))) isTodayTask = true;
        if (task.completedAt && isTodayLocal(new Date(task.completedAt))) isTodayTask = true;
        showDate = task.createdAt;
        todaySpent = task.timeSpent || 0;
      }
      if (isTodayTask) {
        todayTasks.push({
          title: task.title,
          date: showDate,
          hours: (Math.round(todaySpent / 360) / 10).toFixed(1),
          tags: Array.isArray(task.tags) ? task.tags : [],
        });
      }
    }
    callback(todayTasks);
  }
  if (window.chrome && chrome.storage && chrome.storage.local) {
    chrome.storage.local.get(['taskTrackerTasks'], function(result) {
      filterTasks(result.taskTrackerTasks || []);
    });
  } else {
    const tasks = JSON.parse(localStorage.getItem('taskTrackerTasks') || '[]');
    filterTasks(tasks);
  }
}

document.addEventListener('DOMContentLoaded', function() {
  // ... existing code ...

  // Show Today's Tasks 按钮事件
  var showTodayBtn = document.getElementById('show-today-tasks-btn');
  if (showTodayBtn) {
    showTodayBtn.onclick = function() {
      getTodayTasks(function(tasks) {
        const tbody = document.querySelector('#today-tasks-table tbody');
        tbody.innerHTML = '';
        if (!tasks || tasks.length === 0) {
          const tr = document.createElement('tr');
          const td = document.createElement('td');
          td.colSpan = 4;
          td.textContent = 'No tasks.';
          tr.appendChild(td);
          tbody.appendChild(tr);
        } else {
          tasks.forEach(task => {
            const tr = document.createElement('tr');
            // 任务名
            const tdName = document.createElement('td');
            tdName.textContent = task.title || '-';
            tr.appendChild(tdName);
            // 日期
            const tdDate = document.createElement('td');
            tdDate.textContent = task.date ? (new Date(task.date)).toLocaleDateString() : '-';
            tr.appendChild(tdDate);
            // 时长
            const tdHours = document.createElement('td');
            tdHours.textContent = task.hours;
            tr.appendChild(tdHours);
            // 标签
            const tdTags = document.createElement('td');
            if (task.tags && task.tags.length > 0) {
              tdTags.textContent = task.tags.join(', ');
            } else {
              tdTags.textContent = '-';
            }
            tr.appendChild(tdTags);
            tbody.appendChild(tr);
          });
        }
        document.getElementById('today-tasks-modal').style.display = 'flex';
      });
    };
  }
  var closeTodayBtn = document.getElementById('close-today-tasks-btn');
  if (closeTodayBtn) {
    closeTodayBtn.onclick = function() {
      document.getElementById('today-tasks-modal').style.display = 'none';
    };
  }
  var closeTodayModalX = document.getElementById('close-today-tasks-modal');
  if (closeTodayModalX) {
    closeTodayModalX.onclick = function() {
      document.getElementById('today-tasks-modal').style.display = 'none';
    };
  }
  var todayTasksModal = document.getElementById('today-tasks-modal');
  if (todayTasksModal) {
    todayTasksModal.addEventListener('click', function(e) {
      if (e.target === todayTasksModal) {
        todayTasksModal.style.display = 'none';
      }
    });
  }
}); 